/**
 * Copyright (c) 2024 - CARThunder
 * All Rights Reserved by Chengdu CARThunder Intelligent Technology Co., LTD and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with CARThunder in writing by applicable law.
 * <p>
 * <p>
 * file description.
 *
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-07-30              zhihuazhang         Create it.
 * <p>
 * file description.
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-07-30              zhihuazhang         Create it.
 */

/**
 * file description.
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 *
 *      Edit History
 *      ----------------------------------------------------------------------------
 *      DATE                     NAME               DESCRIPTION
 *      2024-07-30              zhihuazhang         Create it.
 *
 */

package com.cart.musicdemo.base.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;

import com.cart.musicdemo.R;
import com.cart.musicdemo.model.SongModel;
import com.umeng.commonsdk.debug.D;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

/**
 * The type File utils.
 */
public class FileUtils {

    private static final Integer BUFFER_SIZE = 8192;

    private static final Integer RADIX = 16;

    private static final MediaMetadataRetriever MMR = new MediaMetadataRetriever();

    private static final float BASE = 200;

    private static Bitmap DEFAULT_ALBUM_PICTURE;

    /**
     * Calculate file hash string.
     *
     * @param filePath the file path
     * @return the string
     */
    public static String calculateFileHash(String filePath) {
        try {
            // 创建 MessageDigest 对象,指定算法为 MD5
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 打开文件输入流
            FileInputStream fis = new FileInputStream(filePath);

            // 创建一个 byte 数组用于读取文件内容
            byte[] buffer = new byte[BUFFER_SIZE];
            int length;

            // 读取文件内容并更新 MessageDigest
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }

            // 关闭文件输入流
            fis.close();

            // 获取 MD5 值并转换为字符串
            byte[] digest = md.digest();
            return new BigInteger(1, digest).toString(RADIX);
        } catch (IOException | NoSuchAlgorithmException exception) {
            exception.printStackTrace();
            return "";
        }
    }

    /**
     * 封面图片解析.
     *
     * @return bitmap
     */
    public static Bitmap getCoverImage(Context context, SongModel songModel) {
        //设置数据源
        MMR.setDataSource(songModel.getPath());
        //获取图片数据
        byte[] data = MMR.getEmbeddedPicture();
        Bitmap albumPicture = null;
        if (data != null) {
            //获取bitmap对象
            albumPicture = BitmapFactory.decodeByteArray(data, 0, data.length);
            //获取宽高
            int width = albumPicture.getWidth();
            int height = albumPicture.getHeight();
            // 创建操作图片用的Matrix对象
            Matrix matrix = new Matrix();
            // 计算缩放比例
            float sx = (BASE / width);
            float sy = (BASE / height);
            // 设置缩放比例
            matrix.postScale(sx, sy);
            // 建立新的bitmap，其内容是对原bitmap的缩放后的图
            albumPicture = Bitmap.createBitmap(
                albumPicture, 0, 0, width, height, matrix, false
            );
        } else {
            if (DEFAULT_ALBUM_PICTURE != null) {
                return DEFAULT_ALBUM_PICTURE;
            }
            //从歌曲文件读取不出来专辑图片时用来代替的默认专辑图片
            albumPicture = BitmapFactory.decodeResource(context.getResources(), R.mipmap.u70);
            int width = albumPicture.getWidth();
            int height = albumPicture.getHeight();
            // 创建操作图片用的Matrix对象
            Matrix matrix = new Matrix();
            // 计算缩放比例
            float sx = (BASE / width);
            float sy = (BASE / height);
            // 设置缩放比例
            matrix.postScale(sx, sy);
            // 建立新的bitmap，其内容是对原bitmap的缩放后的图
            albumPicture = Bitmap.createBitmap(
                albumPicture, 0, 0, width, height, matrix, false
            );
            // 初始化默认封面图片
            DEFAULT_ALBUM_PICTURE = albumPicture;
        }
        return albumPicture;
    }
}
